﻿using HCDV.HCSP;
using hrainwebbase.ashx.testInfo;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web;

namespace hrainwebbase.basecs
{
    public static class JsonControl
    {
        #region JSON传送标志

        /// <summary>
        /// 发生系统错误
        /// </summary>
        public const string Error = "0000";

        /// <summary>
        /// 后台处理成功
        /// </summary>
        public const string Success = "0001";
        /// <summary>
        /// 后台处理失败(如拒绝修改等)
        /// </summary>
        public const string Fail = "0002";
        /// <summary>
        /// 消息
        /// </summary>
        public const string Message = "0003";
        /// <summary>
        /// 超时
        /// </summary>
        public const string SessionOut = "0004";

        /// <summary>
        /// 添加操作
        /// </summary>
        /// 
        public const string Plan = "plan";
        public const string Inseart = "add";
        /// <summary>
        /// 批量插入
        /// </summary>
        public const string InsertList = "addlist";

        /// <summary>
        /// 修改操作
        /// </summary>
        public const string Update = "edit";
        /// <summary>
        /// 删除操作
        /// </summary>
        public const string Delete = "del";
        /// <summary>
        /// 查询
        /// </summary>
        public const string Select = "sel";
        /// <summary>
        /// 审核
        /// </summary>
        public const string Audit = "audit";

        #endregion

        /// <summary>
        /// 格式化为JSON
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string GetJsonStr(string str)
        {
            return string.Format("\"{0}\"", str.Replace("\r\n", "<br>").Replace("\\", "").Replace("\"", ""));
        }

        /// <summary>
        /// Object To Json
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="models">实体数据集</param>
        /// <param name="fields">不需要输出的字段</param>
        /// <returns></returns>
        public static string GetJsonStr<T>(List<T> models, params string[] fields) where T : class
        {
            //if (models.Count == 0)
            //    return "[{}]";
            StringBuilder jsonStr = new StringBuilder("[");

            Type dataType = typeof(T);

            PropertyInfo[] ProList = dataType.GetProperties();

            foreach (var model in models)
            {
                jsonStr.Append("{");
                for (int i = 0; i < ProList.Length; i++)
                {
                    bool write = true;
                    for (int k = 0; k < fields.Length; k++)
                    {
                        if (ProList[i].Name == fields[k])
                        {
                            write = false;
                            break;
                        }
                    }
                    if (write)
                        jsonStr.Append(string.Format("\"{0}\":\"{1}\",", ProList[i].Name, ProList[i].GetValue(model, null)));
                }
                if (ProList.Length > 0)
                    jsonStr.Remove(jsonStr.Length - 1, 1);
                jsonStr.Append("},");
            }
            if (ProList.Length > 0)
                jsonStr.Remove(jsonStr.Length - 1, 1);
            jsonStr.Append("]");
            return jsonStr.ToString();
        }

        /// <summary>
        /// DataTable To Json
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="fields">不需要输出的字段</param>
        /// <returns></returns>
        public static string GetJsonStr(DataTable dt, string subinfo = "", string subinfo2 = "", string subinfo3 = "", string subinfo4 = "", string subinfo5 = "", string subinfo6 = "", string subinfo7 = "", string subinfo8 = "" ,params string[] fields)
        {
            if (dt==null || dt.Rows.Count <= 0)
                return "[]";
            StringBuilder jsonStr = new StringBuilder("[");
            int colNum = dt.Columns.Count;


            string[] subSelectInfo = null;

            if (!string.IsNullOrEmpty(subinfo))
            {
                //"subinfo": "id,taskid,taskno,tasklistid,productname,dkid,dkname,dataaddtime,storeall,lockcout,hasoutall,outstate#hsc_task_store#hsc_task_store#productid-@id,databranchid-" + HCUser.HCUorg + ",storeall-||>||@@hasoutall#id#;//子查询  当前机构 当前物品
                //@XX 一定要在dt数据中
                subSelectInfo = subinfo.Split('#');
            }

          
            foreach (DataRow dr in dt.Rows)
            {
                jsonStr.Append("{");
                #region 子表信息（返回二级树结构）
                jsonStr.Append("\"subinfo\":" + getsumInfo(subinfo, dr) + ",");
                jsonStr.Append("\"subinfo2\":" + getsumInfo(subinfo2, dr) + ",");
                jsonStr.Append("\"subinfo3\":" + getsumInfo(subinfo3, dr) + ",");
                jsonStr.Append("\"subinfo4\":" + getsumInfo(subinfo4, dr) + ",");
                jsonStr.Append("\"subinfo5\":" + getsumInfo(subinfo5, dr) + ",");
                jsonStr.Append("\"subinfo6\":" + getsumInfo(subinfo6, dr) + ",");
                jsonStr.Append("\"subinfo7\":" + getsumInfo(subinfo7, dr) + ",");
                jsonStr.Append("\"subinfo8\":" + getsumInfo(subinfo8, dr) + ",");
                #endregion
                for (int i = 0; i < colNum; i++)
                {
                    bool write = true;
                    for (int k = 0; k < fields.Length; k++)
                    {
                        if (dt.Columns[i].ColumnName == fields[k])
                        {
                            write = false;
                            break;
                        }
                    }
                    if (write)
                        jsonStr.Append(string.Format("\"{0}\":\"{1}\",",
                            dt.Columns[i].ColumnName,
                            //StringDanYinToJSON(dr[i].ToString())
                            dr[i].ToString().Replace("\r\n", "\\r\\n").Replace("\r", "\\r").Replace("\n", "\\n").Replace("\0", "").Replace("\"", "\\\"")
                            ));
                }
                if (colNum > 0)
                    jsonStr.Remove(jsonStr.Length - 1, 1);

                jsonStr.Append("},");
            }
            jsonStr.Remove(jsonStr.Length - 1, 1);
            jsonStr.Append("]");
            return jsonStr.ToString();
        }
        /// <summary>
        /// 子查询信息
        /// </summary>
        /// <param name="subinfo"></param>
        /// <param name="dr"></param>
        /// <returns></returns>
        private static string getsumInfo(string subinfo, DataRow dr)
        {
            string[] subSelectInfo2 = null;

            if (!string.IsNullOrEmpty(subinfo))
            {

                subSelectInfo2 = subinfo.Split('#');


                //productid-@id,databranchid-" + HCUser.HCUorg + "," + suminfowhere + "storehouseid-0,storeall-||>||@@hasoutall,storeall-||like||@@hasoutall,groupby||groupby||采收日期,(HcrDJHHcr)品种ID,(HcrDJHHcr)地块ID,(HcrDJHHcr)datadepid
                DataTable dt_sub;
                string whereInfo = "1=1 ";
                foreach (var winfo in subSelectInfo2[2].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                {
                    var wfileInfo = winfo.Split(new char[] { '-' }, 2,StringSplitOptions.RemoveEmptyEntries);
                    var vfileinfovalue = wfileInfo[1];
                    string scp = "=";//默认的条件符号
                    //分析适配符
                    if (vfileinfovalue.StartsWith("||"))//不是 = 条件 使用指定适配符
                    {
                        vfileinfovalue = vfileinfovalue.Substring(2);
                        scp = vfileinfovalue.Substring(0, vfileinfovalue.IndexOf("||"));
                        vfileinfovalue = vfileinfovalue.Substring(vfileinfovalue.IndexOf("||") + 2);
                    }
                    //分析是 @代表主信息的字段的值  @@ 代表是自表本身的字段   没有代表是值   
                    if (vfileinfovalue.StartsWith("@@"))
                    {
                        if (scp == "like")//不能发生--支持不了从本行取值
                        {
                            whereInfo += string.Format(" and {0} {1} {2}",
                         wfileInfo[0],
                         scp,
                          vfileinfovalue.Replace("@", ""));
                        }
                        else if (scp == "in")
                        {
                            whereInfo += string.Format(" and {0} {1} ({2})",
                          wfileInfo[0],
                          scp,
                           vfileinfovalue.Replace("@", ""));
                        }
                        else
                        {
                            whereInfo += string.Format(" and {0} {1} {2}",
                           wfileInfo[0],
                           scp,
                            vfileinfovalue.Replace("@", ""));
                        }
                    }
                    else
                    {
                        if (scp == "like")
                        {
                            whereInfo += string.Format(" and {0} {1} '%{2}%'",
                                wfileInfo[0],
                                scp,
                                vfileinfovalue.StartsWith("@") ? dr[vfileinfovalue.Replace("@", "")] : vfileinfovalue);
                        }
                        else if (scp == "in")
                        {
                            whereInfo += string.Format(" and {0} {1} ({2})",
                                wfileInfo[0],
                                scp,
                                vfileinfovalue.StartsWith("@") ? dr[vfileinfovalue.Replace("@", "")] : vfileinfovalue);
                        }
                        else if (scp == "groupby")//一定要放在最后一个
                        {
                            whereInfo += string.Format(" GROUP BY  {0} ",
                                vfileinfovalue.StartsWith("@") ? dr[vfileinfovalue.Replace("@", "")] : vfileinfovalue);
                        }
                        else
                        {
                            whereInfo += string.Format(" and {0} {1} '{2}'",
                                wfileInfo[0],
                                scp,
                                vfileinfovalue.StartsWith("@") ? dr[vfileinfovalue.Replace("@", "")] : vfileinfovalue);
                        }
                    }
                }
                //特殊符号还原 HcrDJHHcr='   HcrDHHcr=,
                whereInfo = whereInfo.Replace("(HcrDJHHcr)", "'").Replace("(HcrDHHcr)", ",");
                whereInfo = whereInfo.Replace("HcrDJHHcr", "'").Replace("HcrDHHcr", ",");
                using (dbsimple db = new dbsimple())
                {
                    dt_sub = db.getReportNoPage(subSelectInfo2[1], subSelectInfo2[0], whereInfo, subSelectInfo2[3]);
                }
                var iso = new IsoDateTimeConverter();
                iso.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";//指定时间转换格式

                return JsonConvert.SerializeObject(dt_sub, Formatting.Indented, iso);
            }
            else return "\"\"";
        }
        private static String StringDanYinToJSON(String ors)
        {
            ors = ors == null ? "" : ors;
            StringBuilder buffer = new StringBuilder(ors);
            int i = 0;
            while (i < buffer.Length)
            {
                if (buffer[i] == '\'' || buffer[i] == '\\')
                {
                    buffer.Insert(i, '\\');
                    i += 2;
                }
                else
                {
                    i++;
                }
            }
            return buffer.ToString();
        }

        /// <summary>
        /// 图表特殊处理
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="fields"></param>
        /// <returns></returns>
        public static string GetJsonStrForChar(DataTable dt, params string[] fields)
        {
            if (dt.Rows.Count <= 0)
                return string.Empty;
            StringBuilder jsonStr = new StringBuilder("[");
            int colNum = dt.Columns.Count;
            foreach (DataRow dr in dt.Rows)
            {
                jsonStr.Append("{");
                for (int i = 0; i < colNum; i++)
                {
                    bool write = true;
                    for (int k = 0; k < fields.Length; k++)
                    {
                        if (dt.Columns[i].ColumnName == fields[k])
                        {
                            write = false;
                            break;
                        }
                    }
                    if (write)
                    {
                        if (dt.Columns[i].ColumnName == "value" || dt.Columns[i].ColumnName == "y")//值不加“
                        {
                            jsonStr.Append(string.Format("\"{0}\":{1},", dt.Columns[i].ColumnName, dr[i].ToString().Replace("\0", "")));
                        }
                        else
                            jsonStr.Append(string.Format("\"{0}\":\"{1}\",", dt.Columns[i].ColumnName, dr[i].ToString().Replace("\0", "")));
                    }

                }
                //click: function (data, evt) { jscharclick(data); }
                //jsonStr.Append("click: function (data, evt) { jscharclick(data); },");
                if (colNum > 0)
                    jsonStr.Remove(jsonStr.Length - 1, 1);
                jsonStr.Append("},");
            }
            jsonStr.Remove(jsonStr.Length - 1, 1);
            jsonStr.Append("]");
            return jsonStr.ToString();
        }
        /// <summary>
        /// [Name - Value] To Json
        /// </summary>
        /// <param name="nameArray"></param>
        /// <param name="valueArray"></param>
        /// <returns></returns>
        public static string GetJsonStr(string[] nameArray, object[] valueArray)
        {
            string[] values = new string[valueArray.Length];
            for (int i = 0; i < valueArray.Length; i++)
            {
                if (Object.Equals(valueArray[i], null))
                    values[i] = "";
                else
                    values[i] = valueArray[i].ToString();
            }
            return GetJsonStr(nameArray, values);
        }

        /// <summary>
        /// [Name - Value] To Json
        /// </summary>
        /// <param name="nameArray"></param>
        /// <param name="valueArray"></param>
        /// <returns></returns>
        public static string GetJsonStr(string[] nameArray, string[] valueArray)
        {
            if (nameArray.Length == 0 || valueArray.Length == 0 || valueArray.Length % nameArray.Length != 0)
                return "";
            StringBuilder jsonStr = new StringBuilder("[");
            for (int j = 0; j < valueArray.Length; )
            {
                jsonStr.Append("{");
                for (int i = 0; i < nameArray.Length; )
                {
                    jsonStr.Append(string.Format("\"{0}\":\"{1}\",", nameArray[i++], valueArray[j++]));
                }
                jsonStr.Remove(jsonStr.Length - 1, 1);
                jsonStr.Append("},");
            }
            jsonStr.Remove(jsonStr.Length - 1, 1);
            jsonStr.Append("]");
            return jsonStr.ToString();
        }


        /// <summary>
        /// message,data
        /// </summary>
        /// <param name="result">jsonResultConstStr 必须传入JsonControl中定义的常量</param>
        /// <param name="jsonInfo">JSON格式数据(不可传入未格式化的数据，否则前台无法解析)</param>
        /// <param name="otherDate_Name">其他数据对-名称 ('名称'与'JSON串'个数必须相等)</param>
        /// <param name="otherDate_Json">其他数据对-JSON串</param>
        /// <returns></returns>
        public static string AjaxJsonResult(string result, string jsonInfo, string[] otherDate_Name = null, string[] otherDate_Json = null)
        {
            jsonInfo = jsonInfo.Replace("\r", "").Replace("\n", "");
            StringBuilder jsonStr = new StringBuilder();
            jsonStr.Append("{\"message\":\"");
            jsonStr.Append(result);
            jsonStr.Append("\",\"data\":");
            if (string.IsNullOrEmpty(jsonInfo))
                jsonStr.Append("\"\"");
            else
                jsonStr.Append(jsonInfo);

            if (otherDate_Name != null && otherDate_Json != null && otherDate_Name.Length > 0 && otherDate_Name.Length == otherDate_Json.Length)
            {
                for (int i = 0; i < otherDate_Name.Length; i++)
                {
                    jsonStr.AppendFormat(",\"{0}\":", otherDate_Name[i]);
                    if (string.IsNullOrEmpty(otherDate_Json[i]))
                        jsonStr.Append("\"\"");
                    else
                        jsonStr.Append(otherDate_Json[i]);
                }
            }

            jsonStr.Append("}");

            return jsonStr.ToString();
        }
        public static string AjaxJsonResultNewUI(string result, string jsonInfo)
        {
            jsonInfo = jsonInfo.Replace("\r", "").Replace("\n", "");
            StringBuilder jsonStr = new StringBuilder();
            jsonStr.Append("{\"status\":\"");
            jsonStr.Append(result);
            jsonStr.Append("\",\"info\":");
            if (string.IsNullOrEmpty(jsonInfo))
                jsonStr.Append("\"\"");
            else
                jsonStr.Append(jsonInfo);



            jsonStr.Append("}");

            return jsonStr.ToString();
        }

        /// <summary>
        /// message,pager,data
        /// </summary>
        /// <param name="result">jsonResultConstStr 必须传入JsonControl中定义的常量</param>
        /// <param name="jsonInfo">JSON格式数据(不可传入未格式化的数据，否则前台无法解析)</param>
        /// <returns></returns>
        public static string AjaxJsonResult(string result, string jsonInfo, string pagerInfo)
        {
            jsonInfo = jsonInfo.Replace("\r", "").Replace("\n", "");
            StringBuilder jsonStr = new StringBuilder();
            jsonStr.Append("{\"message\":\"");
            jsonStr.Append(result);
            if (!string.IsNullOrEmpty(pagerInfo))
            {
                jsonStr.Append("\",\"pager\":");
                jsonStr.Append(pagerInfo);
            }
            jsonStr.Append(",\"data\":");
            if (string.IsNullOrEmpty(jsonInfo))
                jsonStr.Append("\"\"");
            else
                jsonStr.Append(jsonInfo);
            jsonStr.Append("}");

            return jsonStr.ToString();
        }

        //public static string AjaxJsonResult(string result, DataTable dt)
        //{
        //    StringBuilder jsonStr = new StringBuilder();
        //    jsonStr.Append("{\"message\":\"");
        //    jsonStr.Append(result);
        //    jsonStr.Append("\",\"data\":");
        //    jsonStr.Append(JsonConvert.SerializeObject(dt));
        //    jsonStr.Append("}");

        //    return jsonStr.ToString();
        //}

        public static string AjaxJsonResultGrid(string result, string jsonInfo, int toal)
        {
            jsonInfo = jsonInfo.Replace("\r", "").Replace("\n", "");
            StringBuilder jsonStr = new StringBuilder();
            jsonStr.Append("{\"message\":\"");
            jsonStr.Append(result);
            jsonStr.Append("\",\"total\":\"");
            jsonStr.Append(toal);

            jsonStr.Append("\",\"rows\":");
            if (string.IsNullOrEmpty(jsonInfo))
                jsonStr.Append("[]");
            else
                jsonStr.Append(jsonInfo);
            jsonStr.Append("}");

            return jsonStr.ToString();
        }
        public static string AjaxJsonResultGridError(string result, string erinfo)
        {
            string jsonInfo = "";
            erinfo = erinfo.Replace("\r", "").Replace("\n", "").Replace(":", "").Replace("\"", "").Replace(",", "");
            StringBuilder jsonStr = new StringBuilder();
            jsonStr.Append("{\"message\":\"");
            jsonStr.Append(result);
            jsonStr.Append("\",\"erinfo\":\"");
            jsonStr.Append(erinfo);
            jsonStr.Append("\",\"total\":\"");
            jsonStr.Append(0);

            jsonStr.Append("\",\"rows\":");
            if (string.IsNullOrEmpty(jsonInfo))
                jsonStr.Append("[]");
            else
                jsonStr.Append(jsonInfo);
            jsonStr.Append("}");

            return jsonStr.ToString();
        }
        public static string AjaxJsonResultGrid(string result, string jsonInfo, int toal, string[] otherDate_Name = null, string[] otherDate_Json = null)
        {
            jsonInfo = jsonInfo.Replace("\r", "").Replace("\n", "");
            StringBuilder jsonStr = new StringBuilder();
            jsonStr.Append("{\"message\":\"");
            jsonStr.Append(result);
            jsonStr.Append("\",\"total\":\"");
            jsonStr.Append(toal);

            jsonStr.Append("\",\"rows\":");
            if (string.IsNullOrEmpty(jsonInfo))
                jsonStr.Append("[]");
            else
                jsonStr.Append(jsonInfo);

            if (otherDate_Name != null && otherDate_Json != null && otherDate_Name.Length > 0 && otherDate_Name.Length == otherDate_Json.Length)
            {
                for (int i = 0; i < otherDate_Name.Length; i++)
                {
                    jsonStr.AppendFormat(",\"{0}\":", otherDate_Name[i]);
                    if (string.IsNullOrEmpty(otherDate_Json[i]))
                        jsonStr.Append("\"\"");
                    else
                        jsonStr.Append(otherDate_Json[i]);
                }
            }

            jsonStr.Append("}");

            return jsonStr.ToString();
        }
        /// <summary>
        /// 包括分页排序信息的数据
        /// </summary>
        /// <param name="itemCount"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public static string GetPagerInfoJson(int itemCount, int pageIndex, int pageSize, string orderField = null, string orderType = null)
        {
            string str = string.Empty;
            if (string.IsNullOrEmpty(orderField))
            {
                orderField = "";
                orderType = "";
            }
            str = GetJsonStr(new string[] { "itemCount", "pageIndex", "pageSize", "orderField", "orderType" },
                new object[] { itemCount, pageIndex, pageSize, orderField, orderType });
            return str;
        }


        public static string GetJsonStrNoSE(string[] nameArray, string[] valueArray)
        {
            if (nameArray.Length == 0 || valueArray.Length == 0 || valueArray.Length % nameArray.Length != 0)
                return "";
            StringBuilder jsonStr = new StringBuilder("");
            for (int j = 0; j < valueArray.Length; )
            {
                jsonStr.Append("{");
                for (int i = 0; i < nameArray.Length; )
                {
                    jsonStr.Append(string.Format("\"{0}\":\"{1}\",", nameArray[i++], valueArray[j++]));
                }
                jsonStr.Remove(jsonStr.Length - 1, 1);
                jsonStr.Append("},");
            }
            jsonStr.Remove(jsonStr.Length - 1, 1);
            jsonStr.Append("");
            return jsonStr.ToString();
        }






        #region  jquery datatables 数据处理
        public static string dtToJsonArray(DataTable dt, params string[] fields)
        {
            if (dt.Rows.Count <= 0)
                return string.Empty;
            StringBuilder jsonStr = new StringBuilder("[");
            int colNum = dt.Columns.Count;
            foreach (DataRow dr in dt.Rows)
            {
                jsonStr.Append("[");
                for (int i = 0; i < colNum; i++)
                {
                    bool write = true;
                    for (int k = 0; k < fields.Length; k++)
                    {
                        if (dt.Columns[i].ColumnName == fields[k])
                        {
                            write = false;
                            break;
                        }
                    }
                    if (write)
                        jsonStr.Append(string.Format("\"{0}\",", dr[i].ToString().Replace("\0", "")));
                }
                if (colNum > 0)
                    jsonStr.Remove(jsonStr.Length - 1, 1);
                jsonStr.Append("],");
            }
            jsonStr.Remove(jsonStr.Length - 1, 1);
            jsonStr.Append("]");
            return jsonStr.ToString();
        }
        #endregion
    }
}